package app.framework.config;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.AnsiSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import java.util.UUID;

@Configuration
@Profile({"sqlite"})
public class DataSource {
	DruidPlugin druid;

	@Value("${db.url}")
	private String dbUrl;
	@Value("${db.username}")
	private String username;
	@Value("${db.password}")
	private String password;

	/* use SPEL expressions */
	@Value("${db.initialSize:#{10}}")
	private int initialSize;
	@Value("${db.minIdle:#{10}}")
	private int minIdle;
	@Value("${db.maxActive:#{50}}")
	private int maxActive;

	/**
	 * 如果不返回DataSource对象
	 * spring在执行scheme.sql和data.sql的内容时
	 * 会自动调用hsql驱动向默认的hsql数据源（内存）初始化数据库。
	 * @return 
	 * @author gulixing@msn.com
	 * @date   2017年1月8日
	 */
//	@Bean //暂时不需要关系型数据库
	public int initDB(){
		 getDataSource(dbUrl, username, password);
		 return 0;
	}

	private javax.sql.DataSource getDataSource(String dbUrl, String username, String password) {
		if(druid !=null){
			return druid.getDataSource();
		}
		druid = new DruidPlugin(dbUrl, username, password);
		druid.setInitialSize(initialSize);
		druid.setMinIdle(minIdle);
		druid.setMaxActive(maxActive);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(UUID.randomUUID().toString(),druid);
		arp.setDialect(new AnsiSqlDialect());
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
		druid.start();
		arp.start();
		return druid.getDataSource();
	}
}